<?php

namespace App\Console\Commands;

use App\Library\Logic\AmountLogic;
use App\Library\Logic\SalesRecordLogic;
use App\Library\Logic\ShopOrderLogic;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class AmountEnterCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:amountEnter';

    /**
     * 用户资金流水日志新表
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $list = SalesRecordLogic::all();
        foreach ($list as $v) {
            if ($v->object_type !== 'shop_order') continue;
            $shopOrder = ShopOrderLogic::detail($v->object_id);
            if (is_null($shopOrder)) continue;
            $item = DB::table('shop_user_price_flowing_log_new')->where('upfl_source_id', $v->order_id)->first();
            $time = null;
            if (!is_null($item)) {
                $time = now()->timestamp($item->created_at);
            } else {
                $time = now();
            }
            $v->status = 1;
            $v->updated_at = $time;
            $v->save();
            $where = ['objectType' => $shopOrder->getTable(), 'objectId' => $shopOrder->order_id, 'type' => 'order'];
            $amount = AmountLogic::findByWhere($where);
            if (is_null($amount)) {
                AmountLogic::insertForModelOfLock(array_merge($where, [
                    'type' => 'order',
                    'title' => '订单结算',
                    'userId' => $shopOrder->sell_user_id,
                    'amount' => $v->amount,
                    'createdAt' => $time,
                    'updatedAt' => $time
                ]));
            }
        }
    }
}
